package com.wfcm.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wfcm.entity.*;
import com.wfcm.service.*;
import com.wfcm.utils.*;
import com.wfcm.wxUitls.SmallOauth;
import com.wfcm.wxUitls.TaskJob;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.IOUtils;
import com.wfcm.annotation.IgnoreSign;
import com.wfcm.annotation.IgnoreToken;
import com.wfcm.wxUitls.Oauth2Token;
import com.wfcm.wxUitls.SNSUserInfo;

@Controller
@RequestMapping("/wx")
@ResponseBody
public class WxController {

	private static  Logger log = LoggerFactory.getLogger(WxController.class);
	 @Autowired
	 private WfMemberService memberService;
	 @Autowired
	 private WfMemberSessionService memberSessionService;
	 @Autowired
	 private WfWxShareService wxShareService;
    @Autowired
    private WfMemberAddressService memberAddressService;
    @Autowired
    private WfMemberChildrenService memberChildrenService;
    @Autowired
    private WfGoodsOrderService goodsOrderService;
    @Autowired
    private WfGoodsOrderRelationService goodsOrderRelationService;
    @Autowired
    private WfCourseChapterService courseChapterService;
    @Autowired
    private WfMemberInvitationService memberInvitationService;
    @Autowired
    private WfMemberCouponsService memberCouponsService;
		
	/** 
	 * 获取微信公众号平台接口的sign 
	 * @return 
	 */  
	@RequestMapping("/sign")
	@ResponseBody
	@IgnoreToken
	public Map<String, Object> sign( HttpServletRequest req) {
		 BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(req.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 String read = IOUtils.readAll(reader);
		 //System.out.println(body);
		JSONObject body = new JSONObject(read);
		
        Map<String, Object> ret = new HashMap<String, Object>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        String jsapi_ticket = "";
        WfWxShareEntity  jsapiTicket = wxShareService.queryObject(2);
        com.alibaba.fastjson.JSONObject jsonObj= FastJSONUtils.getJSONObject(jsapiTicket.getContent());
        //jsapi_ticket = jsonObj.getString("ticket");//我的
        /*if(StringUtils.isBlank(jsapi_ticket)){
            TaskJob job = new TaskJob();
            job.getAccessToken();
            job.getJsapiTicket();
            jsapiTicket = wxShareService.queryObject(2);
            jsonObj= FastJSONUtils.getJSONObject(jsapiTicket.getContent());
            jsapi_ticket = jsonObj.getString("ticket");//我的
        }*/
        jsapi_ticket = jsonObj.getString("jsapi_ticket");//第三方

        String url = body.getString("wxUrl");
        
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        //System.out.println(string1);
//       log.info("******************string1:{}",string1);
        
        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return R.ok(ret);
    }
	
	/**
     * 向指定URL发送GET方法的请求
     *  发送请求的URL
     *  请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     * 
     * 用户同意授权，获取code
     */ 
	@RequestMapping("/authorize")
	@ResponseBody
	@IgnoreToken
    public static void authorize() {
    	String appid = ConstantUtil.GG_APP_ID;//微信公众平台appid
    	//String uri ="wftest.wfkids.net/wx/weixinLogin"; 
    	String uri = urlEncodeUTF8(ConstantUtil.WX_API_PROJECT+"wx/weixinLogin");
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+uri+"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
            
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line =null;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
       /* return  R.ok(result);*/
    }


    /**
     * 向指定URL发送GET方法的请求
     *  发送请求的URL
     *  请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     *
     * 用户同意授权，获取code
     */
    @RequestMapping("/reAuthorize")
    @ResponseBody
    @IgnoreToken
    public static void reAuthorize() {
        String appid = ConstantUtil.GG_APP_ID;//微信公众平台appid
        //String uri ="wftest.wfkids.net/wx/weixinLogin";
        String uri = urlEncodeUTF8(ConstantUtil.WX_API_PROJECT+"wx/authorizeUser");
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+uri+"&response_type=code&scope=userinfo&state=STATE#wechat_redirect";

            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line =null;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        /* return  R.ok(result);*/
    }


    //防止非开发者盗用视频连接，
    @RequestMapping("/authorizeUser")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public void authorizeUser(HttpServletRequest request,HttpServletResponse response) throws Exception {
        // 用户同意授权后，能获取到code
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String[] codes = params.get("code");//拿到code的值
        String code = codes[0];//code
    }


    @RequestMapping("/weixinLogin")
	@ResponseBody
	@IgnoreToken
	@IgnoreSign
	public void weixinLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 用户同意授权后，能获取到code
		Map<String, String[]> params = request.getParameterMap();//针对get获取get参数  
		String[] codes = params.get("code");//拿到code的值 
		String code = codes[0];//code  
		//String[] states = params.get("state");
		//String state = states[0];//state 
		
		//System.out.println("****************code:"+code);
	    // 用户同意授权
        if (!"authdeny".equals(code)) {
        	 // 获取网页授权access_token
            Oauth2Token oauth2Token = getOauth2AccessToken(ConstantUtil.GG_APP_ID, ConstantUtil.GG_APP_SECRET, code);
           // System.out.println("***********************************oauth2Token信息："+oauth2Token.toString());
            // 网页授权接口访问凭证
            String accessToken = oauth2Token.getAccessToken();
            // 用户标识
            String openId = oauth2Token.getOpenId();
            // 获取用户信息
            SNSUserInfo snsUserInfo = getSNSUserInfo(accessToken, openId);
           // System.out.println("***********************************用户信息unionId："+snsUserInfo.getUnionid()+"***:"+snsUserInfo.getNickname());
            // 设置要传递的参数
            
            //判断用户是否存在
    		WfMemberEntity  memberEntity =  memberService.queryByIdentity(snsUserInfo.getUnionid());
//    		String token = null;//用户token
    		if(memberEntity != null){
//    			token = String.valueOf(memberSessionService.createToken(memberEntity.getUserid()).get("token"));
    			/*result.put("token", token);
    			result.put("memberEntity", memberEntity);
    			return result;*/
    			Map<String,Object> map = new HashMap<String,Object>();
    			map.put("token", ISsoLoginHelper.login(memberEntity.getUserid()));
    			map.put("memberEntity", memberEntity.getJSONObject());
     			String url1 = ConstantUtil.WX_PROJECT+"?tokenMap="+urlEncodeUTF8(map.toString());
     			//System.out.println("******************url1:"+url1);
    			response.sendRedirect(url1);
    			return ;
    			//return "http://wftest.wfkids.net/#/bindPhone";
    		}
    		String url2 = ConstantUtil.WX_PROJECT+"bindPhone?from=login&tokenId="+snsUserInfo.getUnionid();
    		
    		System.out.println("******************url2:"+url2);
    		response.sendRedirect(url2); 
    		return ;
        }
	}

	//微信信息获取
    @RequestMapping("/wxVisitorLogin")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public void wxVisitorLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 用户同意授权后，能获取到code
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String param = request.getParameter("param");
        System.out.println("*********************getParameter*param:"+param);
        String[] codes = params.get("code");//拿到code的值
        String code = codes[0];//code
        String inviteId ="" ,id ="",userSource = "",path = "",courseType="";//,flag="",courseId=""
        try {
            param = URLDecoder.decode(param,"UTF-8");
            com.alibaba.fastjson.JSONObject jsonObj= FastJSONUtils.getJSONObject(param);
            inviteId = jsonObj.getString("inviteId");
            id = jsonObj.getString("id");
            userSource = jsonObj.getString("userSource");
            path = jsonObj.getString("path");
            // courseType = jsonObj.getString("courseType");
            System.out.println("*********************decode*param:"+param);
        } catch (Exception e){
            System.out.println("*********************异常");
            e.printStackTrace();
        }

        // 用户同意授权
        if (!"authdeny".equals(code)) {
            // 获取网页授权access_token
            Oauth2Token oauth2Token = getOauth2AccessToken(ConstantUtil.GG_APP_ID, ConstantUtil.GG_APP_SECRET, code);
            // 网页授权接口访问凭证
            String accessToken = oauth2Token.getAccessToken();
            // 用户标识
            String openId = oauth2Token.getOpenId();
            // 获取用户信息
            SNSUserInfo snsUserInfo = getSNSUserInfo(accessToken, openId);
            // 设置要传递的参数

            //判断用户是否存在
            WfMemberEntity  memberEntity =  memberService.queryByIdentity(snsUserInfo.getUnionid());
            if(memberEntity != null){
                if(null == memberEntity.getWxopenid() || null == memberEntity.getWxheadimage() || null == memberEntity.getIdentity() || null == memberEntity.getWxnikename()||
                        0 == memberEntity.getWxopenid().trim().length() || 0 == memberEntity.getWxheadimage().trim().length() || 0 == memberEntity.getIdentity().trim().length() || 0 == memberEntity.getWxnikename().trim().length()){
                    memberEntity.setWxheadimage(snsUserInfo.getHeadImgUrl());
                    memberEntity.setWxopenid(snsUserInfo.getOpenId());
                    memberEntity.setWxnikename(snsUserInfo.getNickname());
                    memberEntity.setIdentity(snsUserInfo.getUnionid());
                    System.out.println("结合wxmember:------------------"+memberEntity.toString());
                    log.info("结合wxmember:------------------"+memberEntity.toString());
                    memberService.update(memberEntity);
                    memberEntity =  memberService.queryByIdentity(snsUserInfo.getUnionid());
                }

                memberEntity.setToken(ISsoLoginHelper.loginGetToken(memberEntity.getUserid()));
                log.info("memberEntity:------------------"+memberEntity.toString());
                String url = "";
                url = ConstantUtil.WX_PROJECT+"?tokenMap="+urlEncodeUTF8(JSON.toJSONString(memberEntity))+"&inviteId="+inviteId+"&id="+id+"&userSource="+userSource+"&path="+path;
                System.out.println("url:------------------"+url);
                response.sendRedirect(url);
                return ;
            }
            String url2 = ConstantUtil.WX_PROJECT+"?openid="+snsUserInfo.getUnionid()+"&nickname="+URLEncoder.encode(snsUserInfo.getNickname(),"utf-8")
                            +"&headImgUrl="+snsUserInfo.getHeadImgUrl()+"&unionid="+snsUserInfo.getUnionid()+"&inviteId="+inviteId+"&id="+id+"&userSource="+userSource+"&path="+path;

            System.out.println("******************url2:"+url2);
            response.sendRedirect(url2);
            return ;
        }
    }


	//最新微信登录
    @RequestMapping("/wxIndexLogin")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public void wxIndexLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 用户同意授权后，能获取到code
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String param = request.getParameter("param");
        System.out.println("*********************getParameter*param:"+param);
        String[] codes = params.get("code");//拿到code的值
        String code = codes[0];//code
        String inviteId ="" ,id ="",userSource = "",path = "",courseType="";//,flag="",courseId=""
        try {
            param = URLDecoder.decode(param,"UTF-8");
            com.alibaba.fastjson.JSONObject jsonObj= FastJSONUtils.getJSONObject(param);
            inviteId = jsonObj.getString("inviteId");
            id = jsonObj.getString("id");
            userSource = jsonObj.getString("userSource");
            path = jsonObj.getString("path");
           // courseType = jsonObj.getString("courseType");
            System.out.println("*********************decode*param:"+param);
        } catch (Exception e){
            System.out.println("*********************异常");
            e.printStackTrace();
        }

        // 用户同意授权
        if (!"authdeny".equals(code)) {
            // 获取网页授权access_token
            Oauth2Token oauth2Token = getOauth2AccessToken(ConstantUtil.GG_APP_ID, ConstantUtil.GG_APP_SECRET, code);
            // 网页授权接口访问凭证
            String accessToken = oauth2Token.getAccessToken();
            // 用户标识
            String openId = oauth2Token.getOpenId();
            // 获取用户信息
            SNSUserInfo snsUserInfo = getSNSUserInfo(accessToken, openId);
            // System.out.println("***********************************用户信息unionId："+snsUserInfo.getUnionid()+"***:"+snsUserInfo.getNickname());
            // 设置要传递的参数
            //判断用户是否存在
            WfMemberEntity  memberEntity =  memberService.queryByIdentity(snsUserInfo.getUnionid());
            if(null == memberEntity){
                WfMemberEntity member = new WfMemberEntity();//创建新用户

                member.setTelephone(null);
                member.setStatus(1);//状态默认为启用
                member.setCreatetime(new Date());
                member.setUpdatetime(new Date());
                member.setUsername(snsUserInfo.getNickname());
                String userPassword = DigestUtils.md5Hex("123456");
                member.setUserpassword(userPassword);
                member.setBlackflag(0);
                member.setWxheadimage(snsUserInfo.getHeadImgUrl());
                member.setWxopenid(snsUserInfo.getOpenId());
                member.setWxnikename(snsUserInfo.getNickname());
                member.setIdentity(snsUserInfo.getUnionid());
                member.setStudyTime(0);
                System.out.println("注册wxmember:------------------"+member.toString());
                log.info("注册wxmember:------------------"+member.toString());
                memberService.save(member);
                memberEntity =  memberService.queryByIdentity(snsUserInfo.getUnionid());

                if(!"".equals(inviteId.trim()) && null != inviteId) {
                    //判断邀请人id是否为空，若不为空，则添加邀请记录
                    WfMemberInvitationEntity memberInvitationEntity = new WfMemberInvitationEntity();
                    memberInvitationEntity.setInviterid(Integer.valueOf(inviteId));
                    memberInvitationEntity.setInvitedid(memberEntity.getUserid());
                    memberInvitationEntity.setCreatetime(new Date());
                    memberInvitationService.save(memberInvitationEntity);

                    //奖励给邀请人 ‘邀请新人奖励券’
                    WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
                    memberCouponsEntity.setUserid(Integer.valueOf(inviteId));
                    memberCouponsEntity.setTitle("邀请新人奖励券");
                    memberCouponsEntity.setCost(20);
                    memberCouponsEntity.setFtype(300);
                    memberCouponsEntity.setLimits(1);
                    memberCouponsEntity.setBeginDate(new Date());
                    Date endDate = DateUtil.getNextMonth(new Date(), 1);
                    memberCouponsEntity.setEndDate(endDate);
                    memberCouponsEntity.setUpdateTime(new Date());
                    memberCouponsEntity.setStatus(2);
                    memberCouponsEntity.setCouponsSource(3);
                    memberCouponsEntity.setReceiveTime(new Date());
                    memberCouponsService.save(memberCouponsEntity);
                }

                //奖励给新人满减券
                WfMemberCouponsEntity memberCouponsEntity = new WfMemberCouponsEntity();
                memberCouponsEntity.setUserid(Integer.valueOf(memberEntity.getUserid()));
                memberCouponsEntity.setTitle("新人注册满减券");
                memberCouponsEntity.setCost(20);
                memberCouponsEntity.setFtype(300);
                memberCouponsEntity.setLimits(1);
                memberCouponsEntity.setBeginDate(new Date());
                Date endDate = DateUtil.getNextDate(new Date(), 7);
                memberCouponsEntity.setEndDate(endDate);
                memberCouponsEntity.setUpdateTime(new Date());
                memberCouponsEntity.setStatus(2);
                memberCouponsEntity.setCouponsSource(100);
                memberCouponsEntity.setReceiveTime(new Date());
                memberCouponsService.save(memberCouponsEntity);

                WfMemberChildrenEntity memberChildrenEntity = new WfMemberChildrenEntity();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                memberChildrenEntity.setChildbirthday(sdf.format(new Date()));
                memberChildrenEntity.setChildname(snsUserInfo.getNickname());
                memberChildrenEntity.setChildsex(1);//性别默认为男（1、男 ； 2、女）
                memberChildrenEntity.setUpdatetime(new Date());
                memberChildrenEntity.setUserid(memberEntity.getUserid());
                memberChildrenEntity.setRegion("北京市");
                memberChildrenService.save(memberChildrenEntity);

            }else if(null == memberEntity.getWxopenid() || null == memberEntity.getWxheadimage() || null == memberEntity.getIdentity() || null == memberEntity.getWxnikename()||
                        0 == memberEntity.getWxopenid().trim().length() || 0 == memberEntity.getWxheadimage().trim().length() || 0 == memberEntity.getIdentity().trim().length() || 0 == memberEntity.getWxnikename().trim().length()){
                memberEntity.setWxheadimage(snsUserInfo.getHeadImgUrl());
                memberEntity.setWxopenid(snsUserInfo.getOpenId());
                memberEntity.setWxnikename(snsUserInfo.getNickname());
                memberEntity.setIdentity(snsUserInfo.getUnionid());
                System.out.println("结合wxmember:------------------"+memberEntity.toString());
                log.info("结合wxmember:------------------"+memberEntity.toString());
                memberService.update(memberEntity);
            }
            Map<String,Object> map = new HashMap();
            log.info("memberEntity:------------------"+memberEntity.toString());
            map.put("token", ISsoLoginHelper.loginGetToken(memberEntity.getUserid()));
            map.put("memberEntity", memberEntity.getJSONObject());
            String url = "";
            url = ConstantUtil.WX_PROJECT+"?tokenMap="+urlEncodeUTF8(map.toString())+"&inviteId="+inviteId+"&id="+id+"&userSource="+userSource+"&path="+path;
            System.out.println("url:------------------"+url);
            response.sendRedirect(url);
            return ;
        }
    }

	@RequestMapping("/weixinLoginBind")
	@ResponseBody
	@IgnoreToken
	@IgnoreSign
	public void weixinLoginBind(HttpServletRequest request,HttpServletResponse response) throws Exception {  
		// 用户同意授权后，能获取到code
		Map<String, String[]> params = request.getParameterMap();//针对get获取get参数  
		String[] codes = params.get("code");//拿到code的值 
		String code = codes[0];//code  
		
		//System.out.println("****************code:"+code);
	    // 用户同意授权
        if (!"authdeny".equals(code)) {
        	 // 获取网页授权access_token
            Oauth2Token oauth2Token = getOauth2AccessToken(ConstantUtil.GG_APP_ID, ConstantUtil.GG_APP_SECRET, code);
            // 网页授权接口访问凭证
            String accessToken = oauth2Token.getAccessToken();
            // 用户标识
            String openId = oauth2Token.getOpenId();
            // 获取用户信息
            SNSUserInfo snsUserInfo = getSNSUserInfo(accessToken, openId);
            //System.out.println("***********************************用户信息unionId："+snsUserInfo.getUnionid()+"***:"+snsUserInfo.getNickname());
            // 设置要传递的参数
            
            //判断用户是否存在
    		WfMemberEntity  memberEntity =  memberService.queryByIdentity(snsUserInfo.getUnionid());
    		if(memberEntity != null){
     			String url1 = ConstantUtil.WX_PROJECT+"bindAccount?errCode=63";
    			response.sendRedirect(url1);
    			return ;
    			//return "http://wftest.wfkids.net/#/bindPhone";
    		}
    		String url2 = ConstantUtil.WX_PROJECT+"bindPhone?from=bind&tokenId="+snsUserInfo.getUnionid();
    		
    		response.sendRedirect(url2);
    		return ;
        }
	}
	
	@RequestMapping("/getOpenid")
	@ResponseBody
	@IgnoreToken
	@IgnoreSign
	public void getOpenid(HttpServletRequest request,HttpServletResponse response) throws Exception {  
		// 用户同意授权后，能获取到code
		Map<String, String[]> params = request.getParameterMap();//针对get获取get参数  
		String[] codes = params.get("code");//拿到code的值 
		String code = codes[0];//code  
		
		System.out.println("****************code:"+code+"*******time:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
	    // 用户同意授权
        if (!"authdeny".equals(code)) {
        	 // 获取网页授权access_token
            Oauth2Token oauth2Token = getOauth2AccessToken(ConstantUtil.GG_APP_ID, ConstantUtil.GG_APP_SECRET, code);
           // System.out.println("***********************************oauth2Token信息："+oauth2Token.toString());
            // 网页授权接口访问凭证
            //String accessToken = oauth2Token.getAccessToken();
            // 用户标识
            String openId = oauth2Token.getOpenId();
            System.out.println("****************openId:"+openId+"*******time:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    		String url2 = ConstantUtil.WX_PROJECT+"makeCartOrder?openId="+openId;
    		
    		System.out.println("******************url2:"+url2);
    		response.sendRedirect(url2); 
    		return ;
        }
	}


	//防止非开发者盗用视频连接，
    @RequestMapping("/getIndexOpenid")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public void getIndexOpenid(HttpServletRequest request,HttpServletResponse response) throws Exception {
        // 用户同意授权后，能获取到code
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String[] codes = params.get("code");//拿到code的值
        String code = codes[0];//code

        // 用户同意授权
        if (!"authdeny".equals(code)) {
            // 获取网页授权access_token
            Oauth2Token oauth2Token = getOauth2AccessToken(ConstantUtil.GG_APP_ID, ConstantUtil.GG_APP_SECRET, code);
            // System.out.println("***********************************oauth2Token信息："+oauth2Token.toString());
            // 网页授权接口访问凭证
            //String accessToken = oauth2Token.getAccessToken();
            // 用户标识
            String openId = oauth2Token.getOpenId();

            String url2 = ConstantUtil.WX_PROJECT+"?openId="+openId;

            //System.out.println("******************url2:"+url2);
            response.sendRedirect(url2);
            return ;
        }
    }

    //防止非开发者盗用视频连接，
    @RequestMapping("/getLoginOpenid")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public void getLoginOpenid(HttpServletRequest request,HttpServletResponse response) throws Exception {
        // 用户同意授权后，能获取到code
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String[] codes = params.get("code");//拿到code的值
        String code = codes[0];//code

        // 用户同意授权
        if (!"authdeny".equals(code)) {
            // 获取网页授权access_token
            Oauth2Token oauth2Token = getOauth2AccessToken(ConstantUtil.GG_APP_ID, ConstantUtil.GG_APP_SECRET, code);
            // System.out.println("***********************************oauth2Token信息："+oauth2Token.toString());
            // 网页授权接口访问凭证
            //String accessToken = oauth2Token.getAccessToken();
            // 用户标识
            String openId = oauth2Token.getOpenId();

            String url2 = ConstantUtil.WX_PROJECT+"login?openId="+openId;

            //System.out.println("******************url2:"+url2);
            response.sendRedirect(url2);
            return ;
        }
    }


	@RequestMapping("/getOpenidToPay")
	@ResponseBody
	@IgnoreToken
	@IgnoreSign
	public void getOpenidToPay(HttpServletRequest request,HttpServletResponse response) throws Exception {  
		// 用户同意授权后，能获取到code
		Map<String, String[]> params = request.getParameterMap();//针对get获取get参数  
		String[] codes = params.get("code");//拿到code的值 
		String code = codes[0];//code  
		
	    // 用户同意授权
        if (!"authdeny".equals(code)) {
        	 // 获取网页授权access_token
            Oauth2Token oauth2Token = getOauth2AccessToken(ConstantUtil.GG_APP_ID, ConstantUtil.GG_APP_SECRET, code);
           // System.out.println("***********************************oauth2Token信息："+oauth2Token.toString());
            // 网页授权接口访问凭证
            //String accessToken = oauth2Token.getAccessToken();
            // 用户标识
            String openId = oauth2Token.getOpenId();
         
    		String url2 = ConstantUtil.WX_PROJECT+"myOrder?openId="+openId;
    		
    		//System.out.println("******************url2:"+url2);
    		response.sendRedirect(url2); 
    		return ;
        }
	}  
	
	@RequestMapping("/getOpenidToRecharge")
	@ResponseBody
	@IgnoreToken
	@IgnoreSign
	public void getOpenidToRecharge(HttpServletRequest request,HttpServletResponse response) throws Exception {  
		// 用户同意授权后，能获取到code
		Map<String, String[]> params = request.getParameterMap();//针对get获取get参数  
		String[] codes = params.get("code");//拿到code的值 
		String code = codes[0];//code  
		
		//System.out.println("****************code:"+code);
	    // 用户同意授权
        if (!"authdeny".equals(code)) {
        	 // 获取网页授权access_token
            Oauth2Token oauth2Token = getOauth2AccessToken(ConstantUtil.GG_APP_ID, ConstantUtil.GG_APP_SECRET, code);
            //System.out.println("***********************************oauth2Token信息："+oauth2Token.toString());
            // 网页授权接口访问凭证
            //String accessToken = oauth2Token.getAccessToken();
            // 用户标识
            String openId = oauth2Token.getOpenId();
         
    		String url2 = ConstantUtil.WX_PROJECT+"coin?openId="+openId;
    		
    		//System.out.println("******************url2:"+url2);
    		response.sendRedirect(url2); 
    		return ;
        }
	}


    /**
     * 获取网页授权凭证接口
     *
     * @return WeixinAouth2Token
     */
    @RequestMapping("/getOauthAccessToken")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public R getOauthAccessToken(HttpServletRequest request) {
        String code = request.getParameter("code");
        System.out.println("code--------------"+code);
        int toUserId = ISsoLoginHelper.confirm(request);//参团人id
        Oauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", ConstantUtil.GG_APP_ID);
        requestUrl = requestUrl.replace("SECRET", ConstantUtil.GG_APP_SECRET);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(requestUrl));
        if (null != jsonObject) {
            try {
                wat = new Oauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInteger("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));

                System.out.println(
                       "wat:------------------"+ wat.toString()
                );

                WfMemberEntity member = memberService.queryWx(toUserId);
                if(member!=null){
                    SNSUserInfo userInfo = this.getSNSUserInfo(jsonObject.getString("access_token"),jsonObject.getString("openid"));
                    System.out.println("userInfo:------------------"+userInfo.toString());
                    member.setWxheadimage(userInfo.getHeadImgUrl());
                    member.setWxopenid(userInfo.getOpenId());
                    member.setWxnikename(userInfo.getNickname());
                    System.out.println("member:------------------"+member.toString());
                    memberService.update(member);
                    System.out.println("member2:------------------"+member.toString());
                }

            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return R.ok().put("OauthToken",wat);
    }


    /**
     * 获取网页授权凭证接口
     *
     * @return WeixinAouth2Token
     */
    @RequestMapping("/appOauthAccessToken")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public R appOauthAccessToken(HttpServletRequest request) {
        String code = request.getParameter("code");
        System.out.println("code--------------"+code);
        int toUserId = ISsoLoginHelper.confirm(request);//参团人id
        Oauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", ConstantUtil.APP_ID);
        requestUrl = requestUrl.replace("SECRET", ConstantUtil.APP_SECRET);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(requestUrl));
        if (null != jsonObject) {
            try {
                wat = new Oauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInteger("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));

                System.out.println(
                        "wat:------------------"+ wat.toString()
                );

                WfMemberEntity member = memberService.queryWx(toUserId);
                if(member!=null){
                    SNSUserInfo userInfo = this.getSNSUserInfo(jsonObject.getString("access_token"),jsonObject.getString("openid"));
                    System.out.println("userInfo:------------------"+userInfo.toString());
                    member.setWxheadimage(userInfo.getHeadImgUrl());
                    member.setWxopenid(userInfo.getOpenId());
                    member.setWxnikename(userInfo.getNickname());
                    System.out.println("member:------------------"+member.toString());
                    memberService.update(member);
                    System.out.println("member2:------------------"+member.toString());
                }

            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return R.ok().put("OauthToken",wat);
    }

	/**
     * 获取网页授权凭证
     * 
     * @param appId 公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static Oauth2Token getOauth2AccessToken(String appId, String appSecret, String code) {
        Oauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(requestUrl));
        if (null != jsonObject) {
            try {
                wat = new Oauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInteger("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return wat;
    }


    /**
     * 获取网页授权凭证接口
     *
     * @return WeixinAouth2Token
     */
    @RequestMapping("/getVisitorLogin")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public R getVisitorLogin(HttpServletRequest request) {
        String code = request.getParameter("code");
        System.out.println("code--------------"+code);
        Oauth2Token wat = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", ConstantUtil.GG_APP_ID);
        requestUrl = requestUrl.replace("SECRET", ConstantUtil.GG_APP_SECRET);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(requestUrl));
        if (null != jsonObject) {
            try {
                wat = new Oauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInteger("expires_in"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
                System.out.println( "wat:------------------"+ wat.toString() );

                R result = R.ok();
                WfMemberEntity member =  memberService.queryByOpenid(jsonObject.getString("openid"));//根据openId获取用户信息
                SNSUserInfo userInfo = this.getSNSUserInfo(jsonObject.getString("access_token"),jsonObject.getString("openid"));
                if(member!=null){
                    result.put("token", ISsoLoginHelper.login(member.getUserid()));
                    return result;
                }else{
                    String openId =  wat.getOpenId();//游客标识
                    log.debug("openId:"+openId);
                    Map<String,String> map =new  HashMap<String,String>();
                    map.put("wxopenid", openId);
                    String token = "";
                    member = new WfMemberEntity();
                    member.setWxopenid(openId);//微信唯一标识
                    member.setWxheadimage(userInfo.getHeadImgUrl());
                    member.setUsername(userInfo.getNickname());
                    member.setWxnikename(userInfo.getNickname());
                    member.setStatus(1);//状态（0.停用 1.启用）
                    member.setCreatetime(new Date());
                    member.setBlackflag(0);//黑名单(1.是 0.否)
                    String userPassword = DigestUtils.md5Hex("123456");
                    member.setUserpassword(userPassword);
                    memberService.save(member);
                    member =  memberService.queryByIdentity(openId);
                    //返回token
                    result.put("token", ISsoLoginHelper.login(member.getUserid()));
                    return result;
                }
            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return R.error(90,"未获取到网页授权凭证");
    }

    /**
     * 通过网页授权获取用户信息
     * @param accessToken 网页授权接口调用凭证
     * @param openId 用户标识
     * @return SNSUserInfo
     */
    public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
        SNSUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        com.alibaba.fastjson.JSONObject jsonObject =  JSON.parseObject(NetUtil.get(requestUrl));

        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用户的标识
                snsUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性别（1是男性，2是女性，0是未知）
                snsUserInfo.setSex(jsonObject.getInteger("sex"));
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                // 用户特权信息
                List<String> list = JSON.parseArray(jsonObject.getString("privilege"),String.class);
                snsUserInfo.setPrivilegeList(list);
                //与开放平台共用的唯一标识，只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。
                snsUserInfo.setUnionid(jsonObject.getString("unionid"));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return snsUserInfo;
    }

    @RequestMapping("/wxSmallLogin")
    @ResponseBody
    @IgnoreToken
    @IgnoreSign
    public void wxSmallLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 用户同意授权后，能获取到code
        Map<String, String[]> params = request.getParameterMap();//针对get获取get参数
        String[] codes = params.get("code");//拿到code的值
        String code = codes[0];//code
        System.out.println("****************small_code:"+code);
        // 用户同意授权
        if (!"authdeny".equals(code)) {
            // 获取网页授权access_token
            SmallOauth samllOauth = getSmallOauth(ConstantUtil.SMALL_APPID, ConstantUtil.SMALL_SECRET, code);
            // System.out.println("***********************************oauth2Token信息："+oauth2Token.toString());
            // 网页授权接口访问凭证
            String accessToken = samllOauth.getSession_key();
            // 用户标识
            String openId = samllOauth.getOpenId();
            // 获取用户信息
            SNSUserInfo snsUserInfo = getSNSUserInfo(accessToken, openId);
            // System.out.println("***********************************用户信息unionId："+snsUserInfo.getUnionid()+"***:"+snsUserInfo.getNickname());
            // 设置要传递的参数

            //判断用户是否存在
            WfMemberEntity  memberEntity =  memberService.queryByIdentity(samllOauth.getUnionid());
//    		String token = null;//用户token
            if(memberEntity != null){
//    			token = String.valueOf(memberSessionService.createToken(memberEntity.getUserid()).get("token"));
    			/*result.put("token", token);
    			result.put("memberEntity", memberEntity);
    			return result;*/
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("token", ISsoLoginHelper.login(memberEntity.getUserid()));
                map.put("memberEntity", memberEntity.getJSONObject());
                String url1 = ConstantUtil.WX_PROJECT+"?tokenMap="+urlEncodeUTF8(map.toString());
                //System.out.println("******************url1:"+url1);
                response.sendRedirect(url1);
                return ;
                //return "http://wftest.wfkids.net/#/bindPhone";
            }
            String url2 = ConstantUtil.WX_PROJECT+"bindPhone?from=login&tokenId="+snsUserInfo.getUnionid();

            System.out.println("******************url2:"+url2);
            response.sendRedirect(url2);
            return ;
        }
    }

    /**
     * 获取网页授权凭证
     *
     * @param appId 公众账号的唯一标识
     * @param appSecret 公众账号的密钥
     * @param code
     * @return WeixinAouth2Token
     */
    public static SmallOauth getSmallOauth(String appId, String appSecret, String code) {
        SmallOauth samllOauth = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("appid", appId);
        requestUrl = requestUrl.replace("secret", appSecret);
        requestUrl = requestUrl.replace("js_code", code);
        // 获取网页授权凭证
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(requestUrl));
        if (null != jsonObject) {
            try {
                samllOauth = new SmallOauth();

                samllOauth.setOpenId(jsonObject.getString("openid"));
                samllOauth.setSession_key(jsonObject.getString("session_key"));
                samllOauth.setUnionid(jsonObject.getString("unionid"));
                samllOauth.setErrcode(Integer.valueOf(jsonObject.getString("errcode")));
                samllOauth.setErrmsg(jsonObject.getString("errmsg"));
            } catch (Exception e) {
                samllOauth = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
                log.error("获取网页授权凭证失败 errcode:{} errmsg:{}", errorCode, errorMsg);
            }
        }
        return samllOauth;
    }


    /**
     * URL编码（utf-8）
     * 
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
}
